package com.sa.commons.function.randomCode.impl;

import java.awt.Color;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import org.patchca.color.ColorFactory;
import org.patchca.color.SingleColorFactory;
import org.patchca.filter.predefined.CurvesRippleFilterFactory;
import org.patchca.filter.predefined.DiffuseRippleFilterFactory;
import org.patchca.filter.predefined.DoubleRippleFilterFactory;
import org.patchca.filter.predefined.MarbleRippleFilterFactory;
import org.patchca.filter.predefined.WobbleRippleFilterFactory;
import org.patchca.service.ConfigurableCaptchaService;
import org.patchca.utils.encoder.EncoderHelper;
import org.patchca.word.RandomWordFactory;

import com.sa.commons.function.randomCode.inter.RandomPicCreator;


public class RandomPicCreatorImpl implements RandomPicCreator {

	private static ConfigurableCaptchaService cs = null;
	private static ColorFactory cf = null;
	private static RandomWordFactory wf = null;
	private static Random r = new Random();
	private static CurvesRippleFilterFactory crff = null;
	private static MarbleRippleFilterFactory mrff = null;
	private static DoubleRippleFilterFactory drff = null;
	private static WobbleRippleFilterFactory wrff = null;
	private static DiffuseRippleFilterFactory dirff = null;

	/**
	 * 构造图片创建器
	 * @param color
	 * @param maxLen
	 * @param minLen
	 * @param width
	 * @param height
	 */
	public RandomPicCreatorImpl(Color color, int maxLen, int minLen, int width,
			int height) {

		cs = new ConfigurableCaptchaService();
		cf = new SingleColorFactory(color);
		wf = new RandomWordFactory();

		crff = new CurvesRippleFilterFactory(cs.getColorFactory());
		drff = new DoubleRippleFilterFactory();
		wrff = new WobbleRippleFilterFactory();
		dirff = new DiffuseRippleFilterFactory();
		mrff = new MarbleRippleFilterFactory();

		cs.setWordFactory(wf);
		cs.setColorFactory(cf);
		cs.setWidth(width);
		cs.setHeight(height);
		wf.setMaxLength(maxLen);
		wf.setMinLength(minLen);
	}

	/**
	 * 生成图片
	 */
	public String createPic(OutputStream os) {

		switch (r.nextInt(5)) {
		case 0:
			cs.setFilterFactory(crff);
			break;
		case 1:
			cs.setFilterFactory(mrff);
			break;
		case 2:
			cs.setFilterFactory(drff);
			break;
		case 3:
			cs.setFilterFactory(wrff);
			break;
		case 4:
			cs.setFilterFactory(dirff);
			break;
		}

		try {
			String randomCode = EncoderHelper.getChallangeAndWriteImage(cs,
					"png", os);

			return randomCode;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;

	}

	
}
